<template>
  <div>
    <el-dialog
      :visible.sync="EditCateDialogVisibleState"
      @open="getDataById"
      @close="closeEditDialog"
    >
      <el-form :model="editData" :rules="formRules" ref="editCateForm">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editData.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button @click="closeEditDialog">取消</el-button>
        <el-button type="primary" @click="submitEdit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'EditCateDialog',
  props: ['id'],
  computed: {
    EditCateDialogVisibleState: {
      get() {
        return this.$store.state.cate.EditCateDialogVisible
      },
      set() {
        this.$store.commit('cate/EditCateDialogVisibleState', false)
      }
    }
  },
  data() {
    return {
      editData: {},
      // 表单验证规则
      formRules: {
        cat_name: [
          { required: true, message: '请输入分类名称！', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    async getDataById() {
      const { data: res } = await this.$http.get('categories/' + this.id)

      this.editData = res.data
    },
    closeEditDialog() {
      this.$store.commit('cate/EditCateDialogVisibleState', false)
    },
    async submitEdit() {
      const { data: res } = await this.$http.put(
        'categories/' + this.editData.cat_id,
        { cat_name: this.editData.cat_name }
      )

      if (res.meta.status !== 200) return this.$message.error('修改失败！')

      this.$message.success('修改成功！')
      this.$emit('updateList')
      this.closeEditDialog()
    }
  }
}
</script>

<style></style>
